package com.example.yilanchatserver.business.freechat;

import com.example.yilanchatserver.business.freechat.enums.EnumUtils;
import com.example.yilanchatserver.business.freechat.enums.ZhiPuErrorCodes;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.Disposable;
import reactor.core.publisher.FluxSink;

@Slf4j
public class ZhiPuPromptSubscriber implements Subscriber<String>, Disposable {
    private final FluxSink<String> emitter;
    private Subscription subscription;




    private final StringBuilder sb;

    private String history = "";


    public ZhiPuPromptSubscriber(FluxSink<String> emitter) {
        this.emitter = emitter;
        this.sb = new StringBuilder();
    }

    @Override
    public void onSubscribe(Subscription subscription) {
        this.subscription = subscription;
        subscription.request(1);
    }

    @Override
    public void onNext(String data) {
        log.info("ZhiPu返回数据：{}", data);
        try{
            if (history.equals(data) && !history.equals("")) {
                subscription.request(1);
//                emitter.next("");
            } else {
                String content = data;
                if(!content.contains(history)){
                    throw new Exception(content);
                }
                content = content == null ? "" : content.substring(history.length());
                if(EnumUtils.getByCode(ZhiPuErrorCodes.class, content) != null){
                    emitter.next(EnumUtils.getByCode(ZhiPuErrorCodes.class, content).getMessage());
                    throw new Exception(EnumUtils.getByCode(ZhiPuErrorCodes.class, content).getMessage());
                }
                emitter.next(content);
                sb.append(content);
                history = data;
                subscription.request(1);
            }
        }catch (Exception e){
            log.error(e.toString());
            emitter.next("[Error]");
            emitter.complete();
        }


    }

    @Override
    public void onError(Throwable t) {
        log.error("ZhiPu返回数据异常：{}", t.getMessage());
        emitter.error(t);
    }

    @Override
    public void onComplete() {
        log.info("ZhiPu返回数据完成");
        emitter.next("[Done]");
        emitter.complete();
    }

    @Override
    public void dispose() {
        log.warn("ZhiPu返回数据关闭");

        emitter.complete();
    }

}
